import * as UserAPI from '@/Api/user';
import * as RealaccountAPI from '@/Api/realaccount';
import  * as Utils from '@/utils';
let _slideOpen = Utils.getLocalStorageData('slideOpen');
const app = {
  state: {
    language: 'zh-CN',
    errorLog: [],
    realaccountGroup: [], //客户组数据
    userInfo: null,
    slideOpen: _slideOpen === null ? true :_slideOpen,
  },
  mutations: {
    SET_LANGUAGE: (state, language) => {
      state.language = language
    },
    ADD_ERROR_LOG: (state, log) => {
      if (state.errorLog.length < 3) {
        state.errorLog.unshift(log)
      } else {
        state.errorLog.shift();
        state.errorLog.unshift(log)
      }
    },
    SET_USERINFO: (state, info) => {
      state.userInfo = info
    //   console.log('userinfo', info);
    },
    TOGGLE_SIDE_BAR: (state) => {
      state.slideOpen = !state.slideOpen;
    },
    SET_REALGROUP: (state, data) => {
      state.realaccountGroup = data;
    },

  },
  actions: {
    login({commit,dispatch}, form){
      return new Promise((resolve, reject) => {
        UserAPI.login(form)
          .then(res => {
            if (res.code != '0') {
              reject(res);
              return;
            }
            try {
              window.localStorage.setItem('token',res.data.token.toString());
            }
            catch(err) {
              console.log(error);
            }
            if(!this.state.app.slideOpen) {
              dispatch('toggleSideBar')
            }
            resolve(res);
          })
          .catch(error => {
            reject(error);
          })
      })
    },
    getUserInfo({commit, dispatch}){
      return new Promise((resolve, reject) => {
        UserAPI.userInfo()
          .then(res => {
            if (res.code != '0') {
              reject(res);
              return;
            }
            commit('SET_USERINFO', res.data);
            if (this.state.app.realaccountGroup.length <= 0) {
              dispatch('queryRealaccountGroup')
            }
            resolve(res);
          })
          .catch(error => {
            reject(error);
          })
      })
    },
    queryRealaccountGroup({commit}) {
      return new Promise((resolve, reject) => {
        RealaccountAPI.realaccountGroup()
          .then(res => {
            if (res.code != '0') {
              reject(res);
              return;
            }
            commit('SET_REALGROUP', res.data);
            resolve(res);
          })
          .catch(error => {
            reject(error);
          })
      })
    },
    setLanguage({commit}, language) {
      commit('SET_LANGUAGE', language)
    },
    addErrorLog({commit}, log) {
      commit('ADD_ERROR_LOG', log)
    },
    toggleSideBar({commit}) {
      commit('TOGGLE_SIDE_BAR')
      Utils.setLocalStorageData('slideOpen',this.state.app.slideOpen)
    },
  }
}

export default app
